const db = require('../config/database');
const { successResponse, errorResponse } = require('../utils/response');

/**
 * 获取Dashboard数据
 */
const getDashboardData = async (req, res) => {
    try {
        const userId = req.user.id;
        
        // 1. 获取用户基本信息
        const [users] = await db.execute(
            `SELECT id, username, school, grade, avatar, stars, 
                    total_correct, total_wrong, continuous_days, last_login
             FROM users WHERE id = ?`,
            [userId]
        );
        
        if (users.length === 0) {
            return errorResponse(res, '用户不存在', 404);
        }
        
        const user = users[0];
        
        // 2. 获取学习统计
        const [progress] = await db.execute(
            `SELECT 
                COUNT(DISTINCT word_id) as words_learned,
                AVG(mastery_level) as avg_mastery,
                SUM(correct_count) as total_correct,
                SUM(wrong_count) as total_wrong
             FROM user_progress WHERE user_id = ?`,
            [userId]
        );
        
        // 3. 获取宠物信息
        const [pets] = await db.execute(
            'SELECT * FROM pets WHERE user_id = ?',
            [userId]
        );
        
        // 4. 获取今日任务
        const today = new Date().toISOString().split('T')[0];
        const [tasks] = await db.execute(
            `SELECT * FROM daily_tasks 
             WHERE user_id = ? AND task_date = ?
             ORDER BY completed ASC, id ASC`,
            [userId, today]
        );
        
        // 如果今天还没有任务，创建默认任务
        if (tasks.length === 0) {
            await createDailyTasks(userId, today);
            // 重新获取
            const [newTasks] = await db.execute(
                `SELECT * FROM daily_tasks 
                 WHERE user_id = ? AND task_date = ?
                 ORDER BY completed ASC, id ASC`,
                [userId, today]
            );
            tasks.push(...newTasks);
        }
        
        // 5. 获取成就统计
        const [achievements] = await db.execute(
            'SELECT COUNT(*) as count FROM user_achievements WHERE user_id = ?',
            [userId]
        );
        
        // 6. 计算准确率
        const totalAnswers = (user.total_correct || 0) + (user.total_wrong || 0);
        const accuracy = totalAnswers > 0 
            ? Math.round((user.total_correct / totalAnswers) * 100) 
            : 0;
        
        return successResponse(res, {
            user: {
                ...user,
                accuracy
            },
            stats: {
                words_learned: progress[0].words_learned || 0,
                avg_mastery: Math.round(progress[0].avg_mastery || 0),
                total_correct: progress[0].total_correct || 0,
                total_wrong: progress[0].total_wrong || 0,
                achievements_count: achievements[0].count
            },
            pet: pets[0] || null,
            daily_tasks: tasks.map(task => ({
                ...task,
                progress: task.target_count > 0 
                    ? Math.round((task.current_count / task.target_count) * 100) 
                    : 0
            }))
        });
        
    } catch (error) {
        console.error('获取Dashboard数据错误:', error);
        return errorResponse(res, '获取数据失败', 500, error);
    }
};

/**
 * 创建每日任务
 */
async function createDailyTasks(userId, date) {
    try {
        console.log(`📅 为用户 ${userId} 创建 ${date} 的每日任务`);
        
        const tasks = [
            { type: 'login', target: 1, reward: 5, name: '每日签到' },
            { type: 'learn_words', target: 10, reward: 10, name: '学习10个单词' },
            { type: 'review', target: 5, reward: 8, name: '复习5个单词' },
            { type: 'play_game', target: 3, reward: 10, name: '完成3局游戏' },
            { type: 'feed_pet', target: 1, reward: 3, name: '喂养宠物' }
        ];
        
        for (const task of tasks) {
            try {
                await db.execute(
                    `INSERT INTO daily_tasks (user_id, task_date, task_type, target_count, current_count, completed, stars_reward)
                     VALUES (?, ?, ?, ?, 0, FALSE, ?)`,
                    [userId, date, task.type, task.target, task.reward]
                );
                console.log(`  ✅ 创建任务: ${task.name}`);
            } catch (error) {
                // 如果任务已存在（重复键），忽略错误
                if (error.code === 'ER_DUP_ENTRY') {
                    console.log(`  ℹ️  任务已存在: ${task.name}`);
                } else {
                    console.error(`  ❌ 创建任务失败 (${task.name}):`, error.message);
                    throw error;
                }
            }
        }
        
        // 自动完成登录任务
        await db.execute(
            `UPDATE daily_tasks 
             SET current_count = 1, completed = TRUE, completed_at = NOW()
             WHERE user_id = ? AND task_date = ? AND task_type = 'login'`,
            [userId, date]
        );
        console.log('  ✅ 登录任务已自动完成');
        
    } catch (error) {
        console.error('❌ 创建每日任务失败:', error);
        throw error;
    }
}

/**
 * 更新任务进度
 */
const updateTaskProgress = async (req, res) => {
    try {
        console.log('📝 更新任务进度 - 开始');
        console.log('用户ID:', req.user?.id);
        console.log('请求体:', req.body);
        
        const userId = req.user.id;
        // 兼容两种参数格式
        const task_type = req.body.task_type || req.body.taskType;
        
        console.log('任务类型:', task_type);
        
        if (!task_type) {
            console.log('❌ 缺少任务类型参数');
            return errorResponse(res, '缺少任务类型参数', 400);
        }
        
        const today = new Date().toISOString().split('T')[0];
        console.log('今天日期:', today);
        
        // 获取任务
        const [tasks] = await db.execute(
            `SELECT * FROM daily_tasks 
             WHERE user_id = ? AND task_date = ? AND task_type = ?`,
            [userId, today, task_type]
        );
        
        console.log('查询到的任务数量:', tasks.length);
        if (tasks.length > 0) {
            console.log('任务详情:', tasks[0]);
        }
        
        if (tasks.length === 0) {
            console.log('❌ 任务不存在');
            return errorResponse(res, '任务不存在', 404);
        }
        
        const task = tasks[0];
        
        if (task.completed) {
            return successResponse(res, { task }, '任务已完成');
        }
        
        // 更新进度
        const newCount = task.current_count + 1;
        const completed = newCount >= task.target_count;
        
        await db.execute(
            `UPDATE daily_tasks 
             SET current_count = ?, completed = ?, completed_at = ?
             WHERE id = ?`,
            [newCount, completed, completed ? new Date() : null, task.id]
        );
        
        // 如果任务完成，奖励星星
        if (completed && !task.completed) {
            await db.execute(
                'UPDATE users SET stars = stars + ? WHERE id = ?',
                [task.stars_reward, userId]
            );
        }
        
        // 获取更新后的任务
        const [updatedTasks] = await db.execute(
            'SELECT * FROM daily_tasks WHERE id = ?',
            [task.id]
        );
        
        console.log('✅ 任务更新成功');
        return successResponse(res, {
            task: updatedTasks[0],
            stars_earned: completed && !task.completed ? task.stars_reward : 0
        }, completed ? '任务完成！获得星星奖励' : '进度已更新');
        
    } catch (error) {
        console.error('❌ 更新任务进度错误:', error);
        return errorResponse(res, '更新失败', 500, error);
    }
};

module.exports = {
    getDashboardData,
    updateTaskProgress
};

